package ru.usu.gv.gui.frames;

import ru.usu.gv.gui.frames.styles.GUIStyleUtilities;
import ru.usu.gv.styles.StyleUtilities;
import ru.usu.gv.uicomponents.IUIEdgeType;
import ru.usu.gv.uicomponents.UIEdge;
import ru.usu.gv.uicomponents.UIEdgeTypeRegistry;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

/**
 * @author spupyrev
 * 02.11.2008
 */
public class EditEdgeFrame extends JFrame
{
	private UIEdge edge;
	private List<ISaveCallback> saveCallbacks = new ArrayList<ISaveCallback>();

	public EditEdgeFrame(UIEdge edge)
	{
		this.edge = edge;
		setTitle("Редактирование ребра");
		initComponents();
	}

	private void initComponents()
	{
		//SETTINGS
		JPanel settingPanel = new JPanel();
		settingPanel.setLayout(new BoxLayout(settingPanel, BoxLayout.Y_AXIS));

		settingPanel.add(createEdgeEditPanel());

		JPanel applyPanel = createSaveCancelPanel();

		getContentPane().add(settingPanel, BorderLayout.NORTH);
		getContentPane().add(applyPanel, BorderLayout.SOUTH);
		pack();
	}

	private JPanel createSaveCancelPanel()
	{
		//SAVINGS
		JPanel applyPanel = new JPanel();

		//apply
		JButton applyButton = new JButton("Применить");
		applyButton.addActionListener(GUIStyleUtilities.createApplyListener(this, saveCallbacks));
		applyPanel.add(applyButton);

		//cancel
		JButton cancelButton = new JButton("Отмена");
		cancelButton.addActionListener(GUIStyleUtilities.createCancelListener(this));
		applyPanel.add(cancelButton);

		return applyPanel;
	}

	private EditEdgePanelBase createEdgeEditPanel()
	{
		return new EditEdgePanelBase(saveCallbacks, true)
		{
			@Override
			protected String getEdgeColor()
			{
				Color color = edge.getViewItem().getColor();
				return StyleUtilities.encodeColor(color);
			}

			@Override
			protected void setEdgeColor(String encodedColor)
			{
				Color color = StyleUtilities.decodeColor(encodedColor);
				edge.getViewItem().setColor(color);
			}

			@Override
			protected String getEdgeTypeId()
			{
				return edge.getEdgeType().getId();
			}

			@Override
			protected void setEdgeTypeId(String newEdgeTypeId)
			{
				IUIEdgeType newEdgeType = UIEdgeTypeRegistry.findEdgeType(newEdgeTypeId);
				edge.changeEdgeType(newEdgeType);
				edge.draw();
			}
		};
	}

}
